import 'package:boss/color_constant.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/models/store_menu.dart';
import 'package:boss/provider/commodity_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/back_confirmation.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/button/fixed_bottom_double_btn.dart';
import 'package:boss/ui/widget/button/radius_button.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/empty_widget.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:boss/ui/widget/picker/commodityPicker/commodity_picker.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:router/annotation.dart';
import 'package:async/async.dart';

@RouterConfig(MiniProgramCommodityRecommendPage.pageName)
class MiniProgramCommodityRecommendPage extends StatefulWidget {
  static const pageName = '/MiniProgramCommodityRecommendPage';

  @override
  _MiniProgramCommodityRecommendPageState createState() => _MiniProgramCommodityRecommendPageState();
}

class _MiniProgramCommodityRecommendPageState extends BaseState<MiniProgramCommodityRecommendPage> {
  _MiniProgramCommodityRecommendPageState() : super(MiniProgramCommodityRecommendPage.pageName);

  List<Commodity> commodities = [];

  List<Commodity> sortCommodities = [];

  bool isSorting = false;

  String get actionText {
    if (isSorting) {
      return '取消';
    }

    return '保存';
  }

  @override
  Widget build(BuildContext context) {
    return BackConfirmation(
      backConfirmationText: '您有修改没有保存，确定要退出吗?',
      child: Scaffold(
        appBar: CenterTitleAppBar(
          title: '设置店家推荐菜',
          backConfirmationText: '您有修改没有保存，确定要退出吗?',
          actions: [
            LabelButton(
              title: actionText,
              onTap: save,
              padding: EdgeInsets.only(left: 4, top: 2, bottom: 2),
              textStyle: TextStyleConstant().blue_28,
            ),
          ],
        ),
        body: Loader<List<StoreMenu>>(
          loadTask: loadTask,
          builder: (context) {
            if (commodities.isEmpty) {
              return buildEmpty();
            }

            return buildContent();
          },
        ),
      ),
    );
  }

  Future<Result<List<StoreMenu>>> loadTask() async {
    final commodityProvider = Provider.of<CommodityProvider>(context, listen: false);
    final res = await commodityProvider.initData();

    if (res.isValue) {
      res.asValue.value.forEach((category) {
        commodities.addAll(category.commodityList.where((commodity) => !commodity.isH5));
      });
    }

    return res;
  }

  Widget buildEmpty() {
    return EmptyWidget(
      title: '尚未添加推荐菜，添加后优先展示，提升销量',
      btnText: '添 加',
      onTap: pickerCommodity,
    );
  }

  Widget buildContent() {
    return Column(
      children: [
        Expanded(
          child: isSorting
              ? ReorderableListView(
                  children: sortCommodities.map((commodity) => buildCommodityRow(commodity)).toList(),
                  onReorder: onReorder,
                )
              : ListView.builder(
                  itemBuilder: (context, index) {
                    final current = commodities[index];

                    return buildCommodityRow(current);
                  },
                  itemCount: commodities.length,
                ),
        ),
        if (!isSorting)
          FixedBottomDoubleBtn(
            first: '添加',
            second: '排序',
            onFirst: pickerCommodity,
            onSecond: sortCommodity,
          ),
        if (isSorting) FixedBottomBtn(title: '确定'),
      ],
    );
  }

  Widget buildCommodityRow(Commodity data) {
    return Container(
      height: 220.w,
      key: ObjectKey(data),
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 30.w - 1.px / 2),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 20.w),
              child: BaseImage(
                data.images,
                width: 160.w,
                height: 160.w,
                borderRadius: BorderRadius.circular(10),
              ),
            ),
            Expanded(
              child: Container(
                constraints: BoxConstraints(minHeight: 160.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      data.title + (data.commodityType == Commodity.COMMODITY_TYPE_PACKAGE ? '[套餐]' : ''),
                      style: TextStyleConstant().normal_1_32.copyWith(fontWeight: FontWeight.bold),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    buildPriceText(data),
                  ],
                ),
              ),
            ),
            if (!isSorting)
              RadiusButton(
                title: '删除',
                width: 100.w,
                height: 40.w,
                onTap: () => deleteSelectedCommodity(data),
                textStyle: TextStyleConstant().blue_24,
                color: ColorConstant.ffdde2fd,
              ),
            if (isSorting)
              BaseImage(
                'assets/image/sort_list_icon.png',
                width: 45.w,
                height: 45.w,
              ),
          ],
        ),
      ),
    );
  }

  Widget buildPriceText(Commodity data) {
    String end = '';

    var priceStr = AmountUtil.price2String(data.price, isFull: true);

    var priceSplit = priceStr.split('.');
    var yuan = priceSplit[0];
    var jf = priceSplit[1];

    return RichText(
      text: TextSpan(
        text: '￥',
        style: TextStyle(fontSize: 20.sp, color: ColorConstant.fe7f76, fontWeight: FontWeight.bold),
        children: [
          TextSpan(
            text: yuan,
            style: TextStyle(fontSize: 36.sp, color: ColorConstant.fe7f76, fontFamily: 'DINAlternate-Bold', fontWeight: FontWeight.bold),
          ),
          TextSpan(
            text: '.$jf',
            style: TextStyle(fontSize: 26.sp, color: ColorConstant.fe7f76, fontFamily: 'DINAlternate-Bold', fontWeight: FontWeight.bold),
          ),
          TextSpan(
            text: '/${data.unit == '' ? '份' : data.unit}$end',
            style: TextStyle(fontSize: 20.sp, color: ColorConstant.fe7f76, fontFamily: 'DINAlternate-Bold', fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
  }

  void pickerCommodity() async {
    final res = await showCommodityPicker(
      context,
      isShowSku: false,
      selectedCommodities: commodities,
    );

    if (res != null) {
      setState(() {
        commodities = res;
      });
    }
  }

  deleteSelectedCommodity(Commodity data) {
    setState(() {
      commodities.remove(data);
    });
  }

  save() {}

  sortCommodity() {
    setState(() {
      sortCommodities = List.from(commodities);
      isSorting = true;
    });
  }

  void onReorder(int oldIndex, int newIndex) {
    setState(() {
      if (oldIndex < newIndex) {
        sortCommodities.insert(newIndex - 1, sortCommodities.removeAt(oldIndex));
      } else {
        sortCommodities.insert(newIndex, sortCommodities.removeAt(oldIndex));
      }
    });
  }
}
